package jam4j.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import java_cup.runtime.ComplexSymbolFactory.Location;

/**
 * Utility methods to assist in parsing using CUP.
 * 
 * @author Luke Maurer
 */
public class Parsing {
    private static final Pattern END_OF_LINE = Pattern.compile("$(?!\\z)");
    
    /**
     * Calculate the location following the given text, assuming it starts at
     * the given location. Advances the line and column count as necessary.
     * 
     * @param start The location at which the text starts.
     * @param text The text.
     * @return The location after the text.
     */
    public static Location afterText(Location start, String text) {
        int line = start.getLine(), column = start.getColumn();
        int lastLineStart = 0;
        Matcher matcher = END_OF_LINE.matcher(text);
        
        while (matcher.find()) {
            line++;
            column = 0;
            lastLineStart = matcher.end();
        }
        
        column += text.length() - lastLineStart;
        
        return new Location(start.getUnit(), line, column);
    }
}
